// --------------------------------------------------------------------------------------------------------------------
// <copyright file="RobotPoseEstimator.cs" company="Microsoft Corporation">
// The MIT License (MIT)
// 
// Copyright (c) 2014, Microsoft Corporation
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//  THE SOFTWARE.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

namespace Microsoft.Robotics.Navigation.Runtime.GroundTruthExtraction
{    
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;

    using Microsoft.Robotics.IO;
    using Microsoft.Robotics.Numerics;
    using Microsoft.Robotics.Tracing;
    using Microsoft.Robotics.Vision.Runtime.GroundTruthExtraction;

    /// <summary>
    /// Robot pose estimator class, which is responsible for estimating the robot pose using the camera pose, landmark point pose and robot
    /// calibration information.
    /// </summary>
    public class RobotPoseEstimator
    {
        /// <summary>
        /// The robot calibration information.
        /// </summary>
        private RobotLandmarkCameraCalibrationInfo calibInfo;

        /// <summary>
        /// Initializes a new instance of the <see cref="RobotPoseEstimator"/> class.
        /// </summary>
        /// <param name="calibrationDataExportFolder">Robot specific calibration folder</param>
        public RobotPoseEstimator(string calibrationDataExportFolder)
        {
            this.calibInfo = DataLoader<RobotLandmarkCameraCalibrationInfo>.ImportData(Path.Combine(calibrationDataExportFolder, "RobotLandmarkCameraCalibrationInfo.xml"));
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="RobotPoseEstimator"/> class.
        /// </summary>
        /// <param name="robotCalibrationInfo">Robot specific calibration info</param>
        public RobotPoseEstimator(RobotLandmarkCameraCalibrationInfo robotCalibrationInfo)
        {
            this.calibInfo = robotCalibrationInfo;
        }
        
        /// <summary>
        /// Gets a value indicating whether the estimator has valid calibration info
        /// </summary>
        public bool HasCalibrationInfo
        {
            get { return this.calibInfo != null; }
        }

        /// <summary>
        /// Estimates the robot pose for the given camera pose and landmark pose using the robot calibration information.
        /// </summary>
        /// <param name="cameraPose">Camera Pose</param>
        /// <param name="landmarkPose">Landmark Pose</param>
        /// <param name="landmarkTiltParams">Landmark tilt parameters</param>
        /// <param name="distanceToLandmark">Distance to the landmark (meters)</param>
        /// <returns>The estimated robot pose or null if it could not be estimated due to robot calibration being not valid</returns>
        public Pose2D? EstimateRobotPose(Pose2D cameraPose, Pose2D landmarkPose, LandmarkTiltParams landmarkTiltParams, double distanceToLandmark)
        {
            if (this.calibInfo == null) 
            {
                TraceOut.Warning(TraceContexts.Nav, "Robot landmark camera calibration is set to null. Returning null for robot pose");
                return null;
            }

            double robotCameraOffsetX = this.calibInfo.RobotToCameraOffsetX;
            double robotCameraOffsetY = this.calibInfo.RobotToCameraOffsetY;

            // Heading of the robot is just the sum of the camera heading with the calibrated offset in heading.
            double heading = cameraPose.Heading + this.calibInfo.RobotToCameraOffsetHeading;
            double cameraAzimuthAngle = this.calibInfo.AzimuthAngle;
            double cameraTiltAngle = this.calibInfo.TiltAngle;
         
            // Rotate the robot offset to be in the current direction of the robot.
            double robotCameraOffsetXRotated = Math.Cos(heading) * robotCameraOffsetX - Math.Sin(heading) * robotCameraOffsetY;
            double robotCameraOffsetYRotated = Math.Sin(heading) * robotCameraOffsetX + Math.Cos(heading) * robotCameraOffsetY;

            Pose2D robotPose = new Pose2D();

            Pose2D cameraCalibratedPose = new Pose2D();
            cameraCalibratedPose.X =
                cameraPose.X - distanceToLandmark * Math.Sin(cameraTiltAngle) * Math.Cos(cameraPose.Heading + cameraAzimuthAngle)
                - distanceToLandmark * Math.Sin(landmarkTiltParams.FloorTiltAngle) * Math.Cos(landmarkTiltParams.FloorAzimuthAngle);
            cameraCalibratedPose.Y = cameraPose.Y - distanceToLandmark * Math.Sin(cameraTiltAngle) * Math.Sin(cameraPose.Heading + cameraAzimuthAngle)
              - distanceToLandmark * Math.Sin(landmarkTiltParams.FloorTiltAngle) * Math.Sin(landmarkTiltParams.FloorAzimuthAngle);
            cameraCalibratedPose.Heading = cameraPose.Heading;

            robotPose.X = cameraCalibratedPose.X + robotCameraOffsetXRotated;

            robotPose.Y = cameraCalibratedPose.Y + robotCameraOffsetYRotated;
            robotPose.Heading = cameraCalibratedPose.Heading + this.calibInfo.RobotToCameraOffsetHeading;

            // Transform the robot pose relative to current landmark onto the global coordinate system (landmark 0).            
            CoordinateTransform2D transform = new CoordinateTransform2D(landmarkPose);
            Pose2D robotAbsolutePose = transform.Transform(robotPose);

            return robotAbsolutePose;
        }
    }
}
